'use strict';

let util = require('util');
let fs = require('fs');
let models = require('../modules/models');
let Fiber = require('fibers');
let csv = require('../modules/lib/csv');
let CsvParser = csv.CsvParser;

let Card = models.Card;
let CardStatus = models.CardStatus;
let School = models.School;
let Classroom = models.Classroom;
let Grade = models.Grade;
let NatureClass = models.NatureClass;
let Student = models.Student;
let FestivalTip = models.FestivalTip;
let Festival = models.Festival;
let Teacher = models.Teacher;
let Attendance = models.Attendance;
let AttendanceValue = models.AttendanceValue;
let AttendanceStatus = models.AttendanceStatus;
let Track = models.Track;
let TrackType = models.TrackType;

let SchoolDao = models.SchoolDao;
let ClassroomDao = models.ClassroomDao;
let GradeDao = models.GradeDao;
let NatureClassDao = models.NatureClassDao;
let StudentDao = models.StudentDao;
let UserDao = models.UserDao;
let CardDao = models.CardDao;
let CheckTimeSetDao = models.CheckTimeSetDao;
let CheckTimeDao = models.CheckTimeDao;
let FestivalTipDao = models.FestivalTipDao;
let FestivalDao = models.FestivalDao;
let TeacherDao = models.TeacherDao;
let AttendanceDao = models.AttendanceDao;
let AttendanceValueDao = models.AttendanceValueDao;
let TrackDao = models.TrackDao;

Fiber(function() {
    let files = fs.readdirSync('utils/data/cards');
    let fullPaths = files.map(file => util.format('utils/data/cards/%s', file));
    let csvParser = new CsvParser();

    let cardReocrdsList = fullPaths.map(fullPath => csvParser.parseFile(fullPath));

    cardReocrdsList.forEach(cardRecords => {
        cardRecords.forEach(cardRecord => {
            if ( cardRecord.card === '' || cardRecord.card === undefined || cardRecord.card === null ) {
                return;
            }
                
            let student = StudentDao.findOne({
                sid: cardRecord.sid
            });

            if ( !student ) {
                console.log(util.format('Student %s is not existed', cardRecord.sid));
                return;
            }

            let card = new Card({
                serialId: cardRecord.card,
                status: CardStatus.Enable
            });
            CardDao.create(card);

            student.cards.push(card);
            StudentDao.update(student);
        });
    });
    
    process.exit();
}).run();

